import { ErrorInfo, FC } from 'react';
import ErrorBoundaryCore from './core';
import { FallbackProps } from './types';
export type HErrorBoundaryProps = {
    children?: React.ReactNode;
    errorLogNoAuth?: (errStr: string) => void;
    onError?: (err?: any) => void;
    fallback: FC<FallbackProps>;
};

const errorToString = (error: Error | ErrorInfo): string => {
    try {
        // 尝试直接转换错误对象
        return JSON.stringify(error);
    } catch (e) {
        // 如果直接转换失败（例如因为循环引用），则返回错误的基本信息
        return `Error:错误转化异常 `;
    }
};

const KErrorBoundary: FC<HErrorBoundaryProps> = ({
    children,
    errorLogNoAuth,
    fallback,
    onError
}) => {
    const handleError = (error: Error, info: ErrorInfo) => {
        console.error(error);
        try {
            onError?.(error);
            errorLogNoAuth &&
                errorLogNoAuth(
                    JSON.stringify({
                        message: error?.message,
                        stack: error?.stack,
                        info: errorToString(info)
                    })
                );
        } catch (e) {
            console.log('上报错误', e);
        }
    };
    return (
        <ErrorBoundaryCore
            onError={handleError}
            fallbackRender={fallback}
        >
            {children}
        </ErrorBoundaryCore>
    );
};
export default KErrorBoundary;
